# -*- coding: utf-8 -*-

import json
from public_util.util.AutoUrl import Route
from django.http import HttpResponse, Http404
from django.shortcuts import render_to_response
from package.models import Material, Project, Channel


@Route()
def material(request):
    """渠道CRUD接口"""
    if request.method == "GET":
        req = request.REQUEST.get
        init = req("init", 0)
        if init:
            pro_objs = Project.filter_project(request)
            return render_to_response("material/material_index.html", locals())
        else:
            objs = Material.filter_record(request)
            item_list = []
            for obj in objs:
                item_list.append([obj.project.pro_name, obj.channel.sdk_name, obj.get_plat_display(),
                                  obj.param_folder, obj.create_time.strftime("%Y-%m-%d %H:%M:%S"), obj.id])
            return HttpResponse(json.dumps({"aaData": item_list}), content_type="application/json")
    elif request.method == "POST":
        err_msg = ""
        params = request.post_dic
        params["project"] = Project.objects.filter(id=params.get("project", 0)).first()
        params["channel"] = Channel.objects.filter(id=params.get("channel", 0)).first()
        _id = request.GET.get("id", 0)
        if _id:
            try:
                Material.objects.filter(id=_id).update(**params)
            except Exception as e:
                err_msg = e
        else:
            try:
                Material(**params).save()
            except Exception as e:
                import traceback
                print(traceback.print_exc())
                err_msg = e
        return render_to_response("feedback.html", locals())


@Route()
def material_detail(request):
    """渠道详情页面接口"""
    plat = Channel.MOBILE_OS_TYPE
    pro_channel_dic = {}
    project_objs = Project.filter_project(request)
    for pro_obj in project_objs:
        pro_channel_dic[pro_obj.id] = [[b.id, b.sdk_name] for b in pro_obj.channel_set.all()]
    _id = request.REQUEST.get("id", 0)
    if _id:
        model = Material.objects.filter(id=_id).first()
        now_channel_lis = pro_channel_dic.get(model.project.id)
    return render_to_response("material/material_detail.html", locals())
